﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace DBUtility
{
    /// <summary>
    /// 数据库访问基类
    /// </summary>
    public class DBHelperSQL
    {
        //数据库连接字符串(web.config来配置)，可以动态更改_connectionString支持多数据库.
        public static string _connstionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        //构造函数
        public DBHelperSQL()
        {
        }

        #region 公用方法
        /// <summary>
        /// 判断某表是否存在某个字段,如Users是否存在id字段
        /// </summary>
        /// <param name="tableName">表名称</param>
        /// <param name="columnName">字段名称</param>
        /// <returns>是否存在,返回bool类型</returns>
        public static bool ColumnExists(string tableName, string columnName)
        {
            string sql = "select count(1) from syscolumns where [id]=object_id('" + tableName + "') and [name]='" + columnName + "'";
            object res = ExecuteScalar(sql);
            if (res == null)
            {
                return false;
            }
            return Convert.ToInt32(res) > 0;
        }

        /// <summary>
        /// 判断表是否存在
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <returns>返回bool类型</returns>
        public static bool TableIsExists(string TableName)
        {
            string strsql = "select count(*) from sysobjects where id = object_id(N'[" + TableName + "]') and OBJECTPROPERTY(id, N'IsUserTable') = 1";
            object obj = ExecuteScalar(strsql);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 获取某个表中某个字段中的最大值
        /// </summary>
        /// <param name="FieldName">字段列</param>
        /// <param name="TableName">表名</param>
        /// <returns>返回最大值,int类型</returns>
        public static int GetMaxColumn(string FieldName, string TableName)
        {
            string strsql = "select max(" + FieldName + ") from " + TableName;
            object obj = ExecuteScalar(strsql);
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return int.Parse(obj.ToString());
            }
        }

        /// <summary>
        /// 根据查询语句判断查询结果是否存在
        /// </summary>
        /// <param name="strSql">查询语句</param>
        /// <returns>返回bool类型</returns>
        public static bool Exists(string strSql)
        {
            object obj = ExecuteScalar(strSql);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 带参数的存在查询语句(重载1)
        /// </summary>
        /// <param name="strSql">查询语句</param>
        /// <param name="cmdParms">参数数组</param>
        /// <returns>返回bool值</returns>
        public static bool Exists(string strSql, params SqlParameter[] cmdParms)
        {
            object obj = ExecuteScalar(strSql, cmdParms);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 根据查询语句判断某条记录结果是否存在(重载2)
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="keyName">表主键字段</param>
        /// <returns>返回bool类型</returns>
        public static bool Exists(string tableName, string keyName)
        {
            string strSql = "select count(1) from {0} where ID={1}";
            strSql = string.Format(strSql, tableName, keyName);

            object obj = ExecuteScalar(strSql);
            int cmdresult;
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                cmdresult = 0;
            }
            else
            {
                cmdresult = int.Parse(obj.ToString());
            }
            if (cmdresult == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        #endregion

        #region  ExecuteNonQuery与ExecuteScalar
        /// <summary>
        /// 执行SQL语句，返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString)
        {
            using (SqlConnection conn = new SqlConnection(_connstionString))
            {
                using (SqlCommand cmd = new SqlCommand(SQLString, conn))
                {
                    try
                    {
                        conn.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        conn.Close();
                        throw e;
                    }
                }
            }
        }

        /// <summary>
        /// 执行SQL语句，返回影响的记录数(重载1)
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <param name="Times">等待命令执行的时间(单位为秒，默认为30秒)</param>
        /// <returns></returns>
        public static int ExecuteSql(string SQLString, int Times)
        {
            using (SqlConnection connection = new SqlConnection(_connstionString))
            {
                using (SqlCommand cmd = new SqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        cmd.CommandTimeout = Times;
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }

        /// <summary>
        /// 执行SQL语句，返回影响的记录数(带参数)(重载2)
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(_connstionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        return rows;
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        throw e;
                    }
                }
            }
        }

        /// <summary>
        /// 执行多条SQL语句，实现数据库事务。
        /// </summary>
        /// <param name="SQLStringList">多条SQL语句</param>		
        public static int ExecuteSqlTran(List<String> SQLStringList)
        {
            using (SqlConnection conn = new SqlConnection(_connstionString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                SqlTransaction tx = conn.BeginTransaction();
                cmd.Transaction = tx;
                try
                {
                    int count = 0;
                    for (int n = 0; n < SQLStringList.Count; n++)
                    {
                        string strsql = SQLStringList[n];
                        if (strsql.Trim().Length > 1)
                        {
                            cmd.CommandText = strsql;
                            count += cmd.ExecuteNonQuery();
                        }
                    }
                    tx.Commit();
                    return count;
                }
                catch
                {
                    tx.Rollback();
                    return 0;
                }
            }
        }

        /// <summary>
        /// 执行一条完整的SQL语句，并返回查询结果
        /// </summary>
        /// <param name="SQLString">完整的SQL语句</param>
        /// <returns>查询结果（object）</returns>
        public static object ExecuteScalar(string SQLString)
        {
            using (SqlConnection connection = new SqlConnection(_connstionString))
            {
                using (SqlCommand cmd = new SqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }

        /// <summary>
        /// 执行一条带参数查询结果语句，返回查询结果(重载1)
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <param name="Times">等待命令执行的时间(单位为秒，默认为30秒)</param>
        /// <returns></returns>
        public static object ExecuteScalar(string SQLString, int Times)
        {
            using (SqlConnection connection = new SqlConnection(_connstionString))
            {
                using (SqlCommand cmd = new SqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        cmd.CommandTimeout = Times;
                        object obj = cmd.ExecuteScalar();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }

        /// <summary>
        /// 执行一条带参数查询结果语句，返回查询结果(重载2)。
        /// </summary>
        /// <param name="SQLString">计算查询结果语句</param>
        /// <param name="cmdParms">参数数组</param>
        /// <returns>查询结果（object）</returns>
        public static object ExecuteScalar(string SQLString, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(_connstionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        object obj = cmd.ExecuteScalar();
                        cmd.Parameters.Clear();
                        if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                        {
                            return null;
                        }
                        else
                        {
                            return obj;
                        }
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                }
            }
        }
        #endregion

        #region DateReader与DataSet
        /// <summary>
        /// 执行查询语句，返回SqlDataReader
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>SqlDataReader</returns>
        public static SqlDataReader ExecuteReader(string strSQL)
        {
            SqlConnection connection = new SqlConnection(_connstionString);
            SqlCommand cmd = new SqlCommand(strSQL, connection);
            try
            {
                connection.Open();
                SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                return myReader;
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                throw e;
            }

        }

        /// <summary>
        /// 执行查询语句，返回SqlDataReader(重载1)
        /// </summary>
        /// <param name="strSQL">查询语句</param>
        /// <returns>SqlDataReader</returns>
        public static SqlDataReader ExecuteReader(string SQLString, params SqlParameter[] cmdParms)
        {
            SqlConnection connection = new SqlConnection(_connstionString);
            SqlCommand cmd = new SqlCommand();
            try
            {
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return myReader;
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                throw e;
            }
        }

        /// <summary>
        /// 返回SqlDataReader
        /// </summary>
        /// <param name="intCount">Top的记录数</param>
        /// <param name="StrFieldName">字段名列表</param>
        /// <param name="StrTableName">表名列表</param>
        /// <param name="StrWhere">条件列表</param>
        /// <param name="StrOrder">排序列表</param>
        /// <returns>返回OleDbDataReader</returns>
        public static SqlDataReader GetDataReader(int intCount, string StrFieldName, string StrTableName, string StrWhere, string StrOrder)
        {
            using (SqlConnection connection = new SqlConnection(_connstionString))
            {
                string strCount = " ";
                SqlDataReader myReader = null;
                DataSet ds = new DataSet();
                try
                {
                    if (intCount > 0)
                    {
                        strCount = " top " + intCount.ToString();
                    }
                    if ((StrFieldName == null) || (StrFieldName.Trim() == ""))
                    {
                        StrFieldName = " * ";
                    }
                    if ((StrWhere == null) || (StrWhere.Trim() == ""))
                    {
                        StrWhere = " ";
                    }
                    else
                    {
                        StrWhere = " where " + StrWhere;
                    }
                    if ((StrOrder == null) || (StrOrder.Trim() == ""))
                    {
                        StrOrder = " ";
                    }
                    else
                    {
                        StrOrder = " order by " + StrOrder;
                    }
                    StringBuilder cmdText = new StringBuilder();
                    cmdText.Append("select " + strCount + " " + StrFieldName + " from " + StrTableName + StrWhere + StrOrder);
                    if (connection.State == ConnectionState.Closed)
                    {
                        connection.Open();
                    }
                    myReader = new SqlCommand(cmdText.ToString(), connection).ExecuteReader(CommandBehavior.CloseConnection);
                    if (connection.State == ConnectionState.Open)
                    {
                        connection.Close();
                    }
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                return myReader;
            }
        }

        /// <summary>
        /// 执行查询语句，返回DataSet
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string SQLString)
        {
            using (SqlConnection connection = new SqlConnection(_connstionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
                    command.Fill(ds, "ds");
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }

        /// <summary>
        /// 执行查询语句，返回DataSet(重载1)
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string SQLString, params SqlParameter[] cmdParms)
        {
            using (SqlConnection connection = new SqlConnection(_connstionString))
            {
                SqlCommand cmd = new SqlCommand();
                PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();
                    try
                    {
                        da.Fill(ds, "ds");
                        cmd.Parameters.Clear();
                    }
                    catch (System.Data.SqlClient.SqlException ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    return ds;
                }
            }
        }

        /// <summary>
        /// 执行查询语句，返回DataSet(重载2)
        /// </summary>
        /// <param name="SQLString">查询语句</param>
        /// /// <param name="Times">执行命令过时时间(单位为秒，默认为30秒)</param>
        /// <returns>DataSet</returns>
        public static DataSet Query(string SQLString, int Times)
        {
            using (SqlConnection connection = new SqlConnection(_connstionString))
            {
                DataSet ds = new DataSet();
                try
                {
                    connection.Open();
                    SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
                    command.SelectCommand.CommandTimeout = Times;
                    command.Fill(ds, "ds");
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }

        /// <summary>
        /// 返回DataSet
        /// </summary>
        /// <param name="intCount">Top的记录数</param>
        /// <param name="StrFieldName">字段名列表</param>
        /// <param name="StrTableName">表名列表</param>
        /// <param name="StrWhere">条件列表</param>
        /// <param name="StrOrder">排序列表</param>
        /// <returns>返回DataSet</returns>
        public static DataSet GetDataSet(int intCount, string StrFieldName, string StrTableName, string StrWhere, string StrOrder)
        {
            using (SqlConnection connection = new SqlConnection(_connstionString))
            {
                DataSet ReturnDs = new DataSet();
                string strCount = " ";
                try
                {
                    if (intCount > 0)
                    {
                        strCount = " top " + intCount.ToString();
                    }
                    if ((StrFieldName == null) || (StrFieldName.Trim() == ""))
                    {
                        StrFieldName = " * ";
                    }
                    if ((StrWhere == null) || (StrWhere.Trim() == ""))
                    {
                        StrWhere = " ";
                    }
                    else
                    {
                        StrWhere = " where " + StrWhere;
                    }
                    if ((StrOrder == null) || (StrOrder.Trim() == ""))
                    {
                        StrOrder = " ";
                    }
                    else
                    {
                        StrOrder = " order by " + StrOrder;
                    }
                    StringBuilder cmdText = new StringBuilder();
                    cmdText.Append("select " + strCount + " " + StrFieldName + " from " + StrTableName + StrWhere + StrOrder);
                    if (connection.State == ConnectionState.Closed)
                    {
                        connection.Open();
                    }

                    SqlCommand cmd = new SqlCommand(cmdText.ToString(), connection);
                    SqlDataAdapter da = new SqlDataAdapter(cmd);

                    if (connection.State == ConnectionState.Open)
                    {
                        connection.Close();
                    }
                    da.Fill(ReturnDs, "ds");
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ReturnDs;
            }
        }
        #endregion

        #region 存储过程操作
        /// <summary>
        /// 执行存储过程，返回SqlDataReader
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlDataReader</returns>
        public static SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters)
        {
            SqlConnection connection = new SqlConnection(_connstionString);
            SqlDataReader returnReader;
            connection.Open();
            SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
            command.CommandType = CommandType.StoredProcedure;
            returnReader = command.ExecuteReader(CommandBehavior.CloseConnection);
            return returnReader;

        }

        /// 执行存储过程，返回影响的行数		
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="rowsAffected">影响的行数</param>
        /// <returns></returns>
        public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected)
        {
            using (SqlConnection connection = new SqlConnection(_connstionString))
            {
                int result;
                connection.Open();
                SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);
                rowsAffected = command.ExecuteNonQuery();
                result = (int)command.Parameters["ReturnValue"].Value;
                //Connection.Close();
                return result;
            }
        }

        /// <summary>
        /// 创建 SqlCommand 对象实例(用来返回一个整数值)	
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlCommand 对象实例</returns>
        private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
        {
            SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
            command.Parameters.Add(new SqlParameter("ReturnValue",
                SqlDbType.Int, 4, ParameterDirection.ReturnValue,
                false, 0, 0, string.Empty, DataRowVersion.Default, null));
            return command;
        }

        /// <summary>
        /// 构建 SqlCommand 对象(用来返回一个结果集，而不是一个整数值)
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlCommand</returns>
        private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
        {
            SqlCommand command = new SqlCommand(storedProcName, connection);
            command.CommandType = CommandType.StoredProcedure;
            foreach (SqlParameter parameter in parameters)
            {
                if (parameter != null)
                {
                    // 检查未分配值的输出参数,将其分配以DBNull.Value.
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    command.Parameters.Add(parameter);
                }
            }

            return command;
        }
        #endregion

        #region 处理参数数组
        /// <summary>
        /// 处理参数数组
        /// </summary>
        /// <param name="cmd">SqlCommand对象</param>
        /// <param name="conn">SqlConnection连接</param>
        /// <param name="trans">事务，若不存在事务应为null</param>
        /// <param name="cmdText">查询语句</param>
        /// <param name="cmdParms">参数数组，若为空应为null</param>
        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;//cmdType;
            if (cmdParms != null)
            {
                foreach (SqlParameter parameter in cmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }
        #endregion
    }
}
